/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package registry

import (
	"fmt"
	"strconv"
	"sync"

	"hundsun.com/hsl/hschain/common/types"

	"hundsun.com/hsl/hschain/common/config"
	"hundsun.com/hsl/hschain/common/log/logging"
	"hundsun.com/hsl/hschain/module/common/utils"
	protoCommon "hundsun.com/hsl/hschain/protos/common"
)

//Service ...
type Service struct {
}

var registryService *Service
var registryServiceOnce sync.Once
var log logging.Log

//GetRegistryServiceInstance 获取注册对象实例
func GetRegistryServiceInstance() *Service {
	registryServiceOnce.Do(func() {
		registryService = &Service{
			//etcdClient: etcd.GetClient(),
		}
		log = logging.GetLogWithCommonConf(logging.ConfigKeyConsoleLogLevel, logging.LogFieldModuleMgt, logging.LogFieldRegistryCenter)
	})
	return registryService
}

//Key ...
func (r *Service) Key(moduleID string) (ModRegKey, error) {
	if len(moduleID) <= 0 {
		return "", types.ErrEmpty
	}
	key := fmt.Sprintf("%s%s", Prefix, moduleID)
	return ModRegKey(key), nil
}

//ConvertModuleConfig2ModRegKV ...
func (r *Service) ConvertModuleConfig2ModRegKV(c *config.ModuleConfig) (*ModRegKV, error) {
	regKv := &ModRegKV{}

	// get key
	key, err := registryService.Key(c.ModuleID)
	if err != nil {
		log.Warnf("failed to generate module registry key with moduleID '%s', p.config.ModuleID")
		return nil, err
	}
	regKv.Key = &key

	// get value
	var value = &ModRegValue{}
	value.ModuleName = c.ModuleName
	value.ModuleID = c.ModuleID
	value.IsMasterStandbyMode = true
	address := &protoCommon.NetworkAddress{}
	address.Host = c.TargetHost
	port, err := strconv.ParseInt(utils.GetPort(c.Parameters), 10, 32)
	if err != nil {
		port = 0
	}
	address.Port = uint32(port)
	value.ListenAddress = address
	value.Extra = make(map[string]interface{})
	regKv.Value = value

	return regKv, nil
}
